package com.zhi_cloud_plat2.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class PictureController {
	@Value("${IMAGE_SERVER_URL}")
	private String IMAGE_SERVER_URL;

	/*
	 * @RequestMapping("/pic/upload")
	 * 
	 * @ResponseBody public Map uploadPicture(MultipartFile uploadFile,
	 * HttpServletRequest request) throws IOException {
	 * 
	 * if(uploadFile.isEmpty()){ System.out.println("文件未上传"); }else{
	 * System.out.println("文件长度: " + uploadFile.getSize()); System.out.println(
	 * "文件类型: " + uploadFile.getContentType()); System.out.println("文件名称: " +
	 * uploadFile.getName()); System.out.println("文件原名: " +
	 * uploadFile.getOriginalFilename());
	 * System.out.println("========================================"); String
	 * realPath ="D:\\upload";
	 * //这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，
	 * 我是看它的源码才知道的 FileUtils.copyInputStreamToFile(uploadFile.getInputStream(),
	 * new File(realPath, uploadFile.getOriginalFilename())); }
	 * 
	 * 
	 * return null; }/zhi_cloud_plat2/src/main/webapp/upload/HOU.jpg
	 */

	@RequestMapping("/pic/upload")
	@ResponseBody
	public Map uploadPicture(MultipartFile uploadFile,HttpServletRequest request) {
		if (uploadFile.isEmpty()) {
			System.out.println("文件未上传");
			return null;
		} else {
			/*String realPath = "D:\\upload";*/
			String realPath = request.getSession().getServletContext().getRealPath("/upload");
			// 这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的
			try {
				FileUtils.copyInputStreamToFile(uploadFile.getInputStream(),new File(realPath, uploadFile.getOriginalFilename()));
				/*String url = "upload/"+uploadFile.getOriginalFilename();*/
				String url = "upload/"+uploadFile.getOriginalFilename();
				Map<String,Object> result = new HashMap<>();
				result.put("error", 0);
				result.put("url", url);
				return result;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Map<String,Object> result = new HashMap<>();
				result.put("error", 1);
				result.put("message", "上传文件失败");
				return result;
			}
		}
	}

}
